package com.data;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.util.Log;

import com.bean.TeachingBean;
import com.constant.Constant;
import com.net.ClientError;
import com.net.ClientException;
import com.net.RequestParameter;
/**
 * 教学名单查询接口
 * 请求参数为：
 * <url> </url> : 请求连接
 * <referer> </referer> : 转发连接
 * 
 * @author mjh
 *
 */
public final class TeachingListData extends BaseData
{
	private final static String TAG = "teaching_list_data";
	/**
	 * 下面三个为请求时添加参数
	 */
	private String mEventTarget;
	private String mEventArgument;
	private String mViewState;
	/**
	 * 当前学年与学期
	 */
	private String mXn;
	private String mXq;
	/**
	 * 教学班信息
	 */
	private ArrayList<String> mClassList;
	/**
	 * 当前选中的教学班号
	 */
	private int mSelectedClass;
	/**
	 * 教学班信息，提交数据时需要
	 */
	private String mBj;
	/**
	 * 默认教学班名单
	 */
	private ArrayList<TeachingBean> mTeachList;
	
	@Override
	public void startParse(RequestParameter parameter) throws Exception, ClientException
	{
		String url 		=	parameter.getValue("url");
		if(url == null)
			throw new NullPointerException("url参数为null");
		String referer 	=	parameter.getValue("referer");
		if ( referer == null )
			throw new NullPointerException("referer参数为null");
			
		parameter.remove("url");
		parameter.remove("referer");
		String text = parameter.getValue("__VIEWSTATE");
		String stream = null;
		if(text == null || text.equals(""))
			stream = openConnection(url, referer, null);
		else 
		{
			String postData = encodeParameters(parameter, "gb2312");
			postData = postData.replaceFirst("&", "");
			stream = openConnection(url, referer, postData);
		}
		
		if ( stream == null )
			return;
		
		readStream(stream);
	}
	
	private String openConnection(final String urlS, final String referer, final String postData) 
			throws IOException,ClientException
	{
		URL url = new URL(urlS);
		
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setConnectTimeout(Constant.SET_CONNECTION_TIMEOUT);
		connection.setReadTimeout(Constant.SET_READ_TIMEOUT);
		connection.setUseCaches(false);
		connection.setDoOutput(true);
		connection.setInstanceFollowRedirects(false);
		
		connection.setRequestProperty("Accept", "text/html, application/xhtml+xml, */*");
		connection.setRequestProperty("Referer", referer);
		connection.setRequestProperty("Host", "jwc.xhu.edu.cn");
		if(postData == null)
		{
			connection.setRequestMethod("GET");
		}
		else
		{
			connection.setRequestMethod("POST");
			OutputStream out = connection.getOutputStream();
			out.write(postData.getBytes());
			out.close();
		}
		connection.connect();
		
		if(connection.getResponseCode() == 200)
		{
			Log.i(TAG, "获取老师教学班信息成功！");
		}
		else
		{
			System.out.println(connection.getResponseCode());
			Log.i(TAG, "获取教学班信息失败，失败信息：" + connection.getResponseCode());
			throw new ClientException(ClientError.ERROR_CONNECTION);
		}
		
		return getWebSource(connection.getInputStream(), "gb2312");
		
	} // openConnection
	
	private void readStream(final String stream)
	{
		Log.i(TAG, "开始解析教学班信息");
		Document document = Jsoup.parse(stream);
		Elements type = document.getElementsByAttributeValueContaining("type", "hidden");
		mEventTarget 	= 	type.get(0).attr("value");
		mEventArgument	=	type.get(1).attr("value");
		mViewState		=	type.get(2).attr("value");
	
		
		// -------------------解析当前教学班信息------------------------------
		
		Elements search_con = document.getElementsByClass("searchbox");
		Elements trs = search_con.select("tr");

		// 获取当前学年信息
		Log.i(TAG, "获取学年信息");
		Element td = trs.get(0).child(0);
		Elements options = td.getElementsByAttributeValueContaining("selected", "selected");
		mXn 	=	options.get(0).ownText();
		mXq 	=	options.get(1).ownText();
		Log.i(TAG, "获取学年学期信息成功");
		
		// 获取当前教学班信息
		td = trs.get(1).child(0);
		options = td.select("option");
		if(options == null)
			return;
		mClassList = new ArrayList<String>();
		mSelectedClass = 0;
		
		for (int i = 0, len = options.size(); i < len; i++ )
		{
			Element option = options.get(i);
			String attr = option.attr("selected");
			if(attr != null && attr.equals("selected"))
				mSelectedClass = i;
			
			String text = option.ownText();
			mClassList.add(text);
		}
		
		Log.i(TAG, "获取教学班号信息成功");
		
		// 获取当前的bj信息
		Element bj = document.getElementById("bj");
//		options = bj.getElementsByAttributeValueContaining("selected", "selected");
//		options = bj.getElementsByAttribute("selected");
		mBj = bj.child(0).ownText();
		Log.e(TAG, mBj);
		
		//System.out.println(bj.html().toString());
		
		Log.i(TAG, "开始解析当前教学班信息名单");
		Elements details = document.getElementsByClass("datelist");
		// 跳过第标题
		Element tr = details.get(0).child(0);
		if(tr== null )
			return;
		
		tr = tr.child(1);
		if(tr == null)
			return;
		mTeachList = new ArrayList<TeachingBean>();
		while(tr != null)
		{
			TeachingBean bean 	= 	new TeachingBean();
			bean.number			=	tr.child(0).ownText();
			bean.name			=	tr.child(1).ownText();
			bean.professionName	=	tr.child(2).ownText();
			bean.clsName		=	tr.child(3).ownText();
			bean.grade			=	tr.child(4).ownText();
			bean.coursecredit	=	tr.child(5).ownText();
			bean.rebulid		=	tr.child(6).ownText();
			mTeachList.add(bean);
			
			tr = tr.nextElementSibling();
		}
		
		Log.i(TAG, "数据解析成功");
	} // readStream

	public String getEventTarget()
	{
		return mEventTarget;
	}

	public String getEventArgument()
	{
		return mEventArgument;
	}

	public String getViewState()
	{
		return mViewState;
	}

	public String getXn()
	{
		return mXn;
	}

	public String getXq()
	{
		return mXq;
	}

	public ArrayList<String> getClassList()
	{
		return mClassList;
	}

	public int getSelectedClass()
	{
		return mSelectedClass;
	}

	public ArrayList<TeachingBean> getTeachList()
	{
		return mTeachList;
	}
	
	public String getBj()
	{
		return this.mBj;
	}
	
	public void printData()
	{
		System.out.println("mEventArgument:" + mEventArgument);
		System.out.println("mEventTarget:" + mEventTarget);
		System.out.println("mViewState:" + mViewState);
		System.out.println("学年：" + mXn);
		System.out.println("学期：" + mXq);
		System.out.println("当前选中教学班：" + mSelectedClass);
		for(int i = 0; i < mClassList.size(); i++)
		{
			System.out.println(mClassList.get(i));
		}
		
		System.out.println("当前教学班信息");
		for(int i = 0; i < mTeachList.size(); i++)
		{
			TeachingBean bean = mTeachList.get(i);
			System.out.println("number: " + bean.number);
			System.out.println("name:" +bean.name);
			System.out.println(bean.professionName);
			System.out.println(bean.clsName);
			System.out.println(bean.grade);
			System.out.println(bean.coursecredit);
			System.out.println(bean.rebulid);
		}
	}
	

} // TeachingListData
